const { app, BrowserWindow, ipcMain, net, Tray, Menu, nativeImage, netLog} = require('electron')
const path = require('path')
const Common = require('./constants').default
import { updater } from './update'
import { readKeystore,createKeystore,saveKeystore, getSecret, secretToPriPub } from './keystore'
import { getBalance, getAccountInfo, transfer, getTransactionInfo, getInitdata,createAccount} from './net'
import { globalShortcut } from 'electron';
import { PassThrough } from 'stream';
// import { platform } from 'os';
const removeKeystore = require('./removeKeystore').default
const fs = require('fs')

// const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080` : `file://${__dirname}/index.html`;
// const iconPath = path.join(__dirname,'../../static/images/icon.ico');
// const naimage = nativeImage.createFromPath(iconPath)
// // const gotTheLock= app.makeSingleInstance()

class DLB_WALLET{
  	constructor(){
		this.walletWindow = null;
		this.appIcon = null;
	};
	
  	init(){
		if(this.checkInstance()) {
			this.initApp();
			this.initIPC();
		}
	};
	
	checkInstance(){
    	const isSecondInstance = app.requestSingleInstanceLock((commandLine, workingDirectory) => {
			// Someone tried to run a second instance, we should focus our window.
		  	if (this.walletWindow) {
			  	if (this.walletWindow.isMinimized()) myWindow.restore()
			  	this.walletWindow.focus()
		   	}
		})
		return isSecondInstance
	};
	
	initApp(){
		app.on('ready',()=>{
			this.createWindow()
			// globalShortcut.register(process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I',()=>{
			// 	this.walletWindow.webContents.openDevTools()
			// })
			// netLog.startLogging(path.join(__dirname,'../../net-log'))
		});
		app.on('activate',()=>{
			if (this.walletWindow == null ) {
				this.createWindow()
			} else {
				this.walletWindow.show()
			}
		});
		app.on('quit',()=>{           
			if (this.walletWindow){
				app.quit()
			}
		})
	};
	
	initIPC(){
		// this.walletWindow.once('ready-to-show',()=>{
		//     console.log('show')
		// })

	  	//隐藏
		ipcMain.on('hide-window', () => {
			this.walletWindow.hide();
		});

		//最小化
		ipcMain.on('minimize-window', () => {
			this.walletWindow.minimize();
		});

		//最大化
		ipcMain.on('maximize-window', () => {
			this.walletWindow.maximize()
		});

		//还原
		ipcMain.on('orignal-window', () => {
			this.walletWindow.unmaximize();
		});

		//关闭
		ipcMain.on('close-window', function () {
			app.quit()
		})

		//更新
		ipcMain.on('check-update',(event,arg)=>{
			updater(event)
		})

		ipcMain.on('log',(event,message)=>{
			console.log(message)
		});

		//初始时间戳
		ipcMain.on('getInitdata',(event)=>{
			console.log('getinitdata')
			getInitdata(function(resp){
				event.sender.send('getInitdata',resp.msg)
			})
		})

		//创建钱包
		ipcMain.on('createAccount',(event,wallet_name,wallet_pwd)=>{
			// var secret = randomstring.generate({length: 88, readable: true, charset: 'alphanumeric'});
			// console.log(secret)
			// var resp_keystore = createKeystore('789456123',secret,wallet_name,wallet_pwd)
			// console.log(resp_keystore)
			// if(resp_keystore.code){
			// 	var resp_save=saveKeystore(resp_keystore.keystore)
			// 	console.log(resp_save)
			// 	event.returnValue = resp_save
			// } else {
			// 	event.returnValue ={code:0,msg:'创建失败'}
			// }
			// console.info('get create account event in mian-process')
			// console.info(wallet_name)
			// console.info(wallet_pwd)
			console.log('create account')
			createAccount(function(resp){
				// console.log(resp)
				if(resp.code){
					if(resp.msg.success){
						createKeystore(resp.msg.publicKey,resp.msg.secret,wallet_name,wallet_pwd,function(resp_create){
							// console.log(resp_create)
							if(resp_create.code){
								saveKeystore(resp_create.keystore,0,function(resp_save){
									// console.log('create account',1)
									event.sender.send('createAccount',resp_save)
								})
							} else {
								// console.log('create account',2)
								event.sender.send('createAccount',resp_create)
							}
						})	 
					}else{
						// console.log('create account',3)
						event.sender.send('createAccount',resp.msg)
					}
				}else{
					// console.log('create account',4)
					event.sender.send('createAccount',resp)
				}
			})
		});

		//导入keystore文件
		ipcMain.on('importKeystore',(event,filepath,pwd,rename)=>{
			// console.log(path.basename(filepath[0]))
			// console.log(Common.DEFAULT_KEYSTORE_PATH+'/'+path.basename(filepath[0]))
			// console.log(filepath)
			// console.log(fs.readFileSync(filepath[0]))
			// var ks = new KEYSTORE();
			// console.log(filepath,pwd,rename)
			var keystore_obj = JSON.parse(fs.readFileSync(filepath))
			getSecret(keystore_obj,pwd,function(resp_gets){
				if (resp_gets.code){
					try{
						var write_path = Common.DEFAULT_KEYSTORE_PATH+"/"+path.basename(filepath)
						var keystore_im = JSON.parse(fs.readFileSync(filepath))
						keystore_im['name'] = rename
						fs.writeFile(write_path,JSON.stringify(keystore_im),function(err){
							if(err){
								event.sender.send('importKeystore',{code:0,msg:err})
							}
						})
					} catch(err){
						event.sender.send('importKeystore',{code:0,msg:err})
					}
					event.sender.send('importKeystore',{code:200,msg:`${write_path} imported successfully`})				
				}  else {
					event.sender.send('importKeystore',resp_gets)
				}
			})	
		})

		//修改密码
		ipcMain.on('changePassword',(event,publicKey,pwd,newPwd)=>{
			console.log('change password',publicKey,pwd,newPwd)
			readKeystore(0,publicKey,function(resp_read){
				if(resp_read.code){
					if (resp_read.keystore_list){
						// console.log('keystore')
						getSecret(resp_read.keystore_list[0],pwd,function(resp_gets){
							if (resp_gets.code){
								// console.log('secret')
								createKeystore(publicKey,resp_gets.secret,resp_read.keystore_list[0].name,newPwd,function(resp_create){
									if(resp_create.code){
										saveKeystore(resp_create.keystore,0,function(resp_save){
											if(resp_save.code){
												removeKeystore(publicKey,pwd,function(resp_remove){
													// console.log(resp)
													if(resp_remove.code){
														event.sender.send('changePassword',{code:200})
													}
												})
											}else{
												event.sender.send('changePassword',resp_save)
											}
										})
									}else{
										event.sender.send('changePassword',resp_create)
									}								
								})	
							} else {
								event.sender.send('changePassword',resp_gets)
							}
						})
					} else {
						event.sender.send('changePassword',{code:0,msg:'wallet no exist'})
					}
				} else {
					event.sender.send('changePassword',resp_read)
				}
			})	
		})

		//删除钱包
		ipcMain.on('remove-wallet',(event,publicKey,pwd)=>{
			removeKeystore(publicKey,pwd,function(resp_remove){
				// console.log(resp_remove)
				event.sender.send('remove-wallet',resp_remove)
			})           
		})

		//转账交易
		ipcMain.on('sendMoney',(event,sendPublic,pwd,recipient,amount)=>{
			readKeystore(0,sendPublic,function(resp_read){
				if(resp_read.code){
					getSecret(resp_read.keystore_list[0],pwd,function(resp_gets){
						if (resp_gets.code){
							transfer(sendPublic,resp_gets.secret,recipient,amount,function(resp_transfer){
								event.sender.send('sendMoney',resp_transfer)
							})
						} else {
							event.sender.send('sendMoney',resp_gets)
						}           
					})
				}else{
					event.sender.send('sendMoney',resp_read)
				}
			})
		});

		//余额查询
		ipcMain.on('getBalances',(event,publicKey)=>{
			console.log('getBalances')
			// secretToPriPub('serwerwerwwerw',function(resp){
			// 	console.log(resp)
			// })
			var balance_list = new Array()
			if (publicKey){
				// console.log('getBalances')
				getBalance(publicKey,function(resp){
					if(resp.success){
						balance_list.push({publicKey:publicKey,balance:resp.balance})
					} else {
						balance_list.push({publicKey:publicKey,balance:''})
					}					
				})
				event.sender.send('getBalances',balance_list)			
			} else {
				readKeystore(0,0,function(resp_read){
					if(resp_read.code){
						// console.info(keystore_list)
						var actions = []
						// keystore_list.push({})

						for (let index = 0; index < resp_read.keystore_list.length; index++) {
							const file = resp_read.keystore_list[index];
							var action =()=>{
								return new Promise(resolve=>{
									((index)=>{
										getBalance(file.publicKey,function(resp){
											// console.log(resp)
											if(resp.success){
												balance_list.push({publicKey:file.publicKey,balance:resp.dlbBalance})
											} else {
												balance_list.push({publicKey:file.publicKey,balance:''})
												// console.log(balance_list)
											}
										resolve();	
										})
									})(index)
								})	
							}
							actions.push(action());
						}
						Promise.all(actions).then(()=>{
							// console.log(balance_list)
							event.sender.send('getBalances',balance_list)
						})
					}else{
						event.sender.send('getBalances',[])
					}
				})
			}		
		});

		//获取账户信息
		ipcMain.on('get-Account-Info',(event,key,page,num)=>{
			console.log('get account info ')
			if(key){
				getAccountInfo(key,page,num,function(resp){
					event.sender.send('get-Account-Info',resp.msg)
				})
			}
		})

		//获取交易信息
		ipcMain.on('getTransactionInfo',(event,hash)=>{
			if (hash){
				getTransactionInfo(hash,function(resp){
					event.sender.send('getTransactionInfo',resp)
				})
			}
		})

		//获取私钥
		ipcMain.on('get-private',(event,publicKey,pwd)=>{
			readKeystore(0,publicKey,function(resp_read){
				if(resp_read.code){
					getSecret(resp_read.keystore_list[0],pwd,function(resp_gets){
						if(resp_gets.code){
							secretToPriPub(resp_gets.secret,function(resp_secret){
								if(resp_secret.code){
									event.sender.send('get-private',resp_secret.privateKey)
								}else{
									event.sender.send('get-private',resp_secret)
								}
							})
						}else{
							event.sender.send('get-private',resp_gets)
						}
					})
				}else{
					event.sender.send('get-private',resp_read)
				}
			})
		})

		//获取当前钱包信息
		ipcMain.on('show-wallet',(event)=>{
			// var ks = new KEYSTORE();
			console.log('show wallet')
			readKeystore(0,0,function(resp){
				// console.log(resp)
				event.sender.send('show-wallet',resp.keystore_list)
				// console.log(resp.keystore_list)
			})
			
		})

		//导出钱包
		ipcMain.on('export-wallet',(event,publicKey,path)=>{
			readKeystore(0,publicKey,function(resp){
				if(resp.code){
					// console.log(resp)
					fs.writeFile(path+'/'+resp.filename,JSON.stringify(resp.keystore_list[0]),function(err){
						if(err){
							event.sender.send('export-wallet',{code:0,msg:err})
						}else{
							event.sender.send('export-wallet',{code:200})
						}
					})
				}else{
					event.sender.send('export-wallet',{code:0,msg:resp.msg})
				}
			})
		})

		//
		ipcMain.on('versions',(event)=>{
			const package_info = require('../../package.json')
			event.sender.send('version',package_info.version)
		})

		ipcMain.on('test',(event,s)=>{
			// var format = require('string-format')
			var process = require('child_process');
			var comand = 'node ./src/main/test.js '+'\"'+s+'\"'
			console.log(comand)
			process.exec(comand,function(error,stdout,stderr){
				console.log(error,stdout,stderr)
			})
		})

		//给用户转测试网的币
		ipcMain.on('test_coin',(event,address)=>{
			console.log("test_coin",address)
			if (!address){
				event.sender.send('test_coin',{code:0,msg:"address 不存在"})
			}else{
				getBalance(address,function(resp){
					if(resp.success){
						if(~resp.balance <= 0){
							var sendPublic= "451a74ca0225c3c99e5481ff22b5c265092a5129123e7621cc50e1048743dc6e"
							var secret = "happy come now friend meaning I beautiful together kind air morning love philosophy"
							transfer(sendPublic,secret,address,100,function(resp_transfer){
								// console.log(resp)
								event.sender.send('test_coin',resp_transfer)
							})
						}else{
							event.sender.send('test_coin',{code:0,msg:"账户币不为0"})
						}
					} else {
						event.sender.send('test_coin',{code:0,msg:resp.message})
					}	
				})		
			}	
		})
	}

  	createWindow(){
		const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080` : `file://${__dirname}/index.html`;
		// const iconPath = path.join(__dirname,'static/images/icon.ico');
		if (process.env.NODE_ENV !== 'development') {
			global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
		}
		const iconPath = `${__static}/images/48x48.png`

		this.walletWindow = new BrowserWindow({
			title:'DLB wallet',
			width: 980,
			height: 672,
			minWidth: 980,
			minHeight: 672,
			transparent: true,
			useContentSize: true,
			icon: iconPath,
			iconNativeImage: iconPath,
			frame: false, //创建无边框窗口
			resizable: false, //改变窗口size,
			autoHideMenuBar:false,
			webPreferences:{
				javascript:true,
				plugins:true,
				nodeIntegration:true,
				webSecurity:false,
			}
		});

		this.walletWindow.on('close',() => {  
			//回收BrowserWindow对象  
			this.walletWindow = null;  
		});  

		this.walletWindow.loadURL(winURL)
		this.appIcon = new Tray(iconPath)

		const contextMenu = Menu.buildFromTemplate([
			{
				label: "打开面板",
				click:()=>{
					if (this.walletWindow){
						this.walletWindow.show()
					}
				}
			},
			{
				label: "退出",
				click:()=>{
					if(this.walletWindow){
						app.quit()
						process.crash()
					}
				}
			}
		])
		this.appIcon.setToolTip('DLB WALLET')
		this.appIcon.setContextMenu(contextMenu)
		this.appIcon.on('click',()=>{
			if (this.walletWindow){
				this.walletWindow.show()
			}
		})

	}
}

new DLB_WALLET().init()